package chatGUI;
import network.*;
import chatControler.*;

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.net.InetAddress;

import javax.swing.*;



public class GUI extends JFrame {
	
	ChatNI net;
	PerformConnexion performConnex;
	PerformDisconnect performDisconnex;
	
	private JTextField login;
	private JButton bSend;
	private JButton connect;
	private JButton disconnect;
	private JTextArea textRec;
	private JTextArea textToSend;
	
	final static int listeningPort = 1234;
	final static int portDest = 4321;
	
	static UdpReceiver testUDPReceiveText; //= new UdpReceiver(portDest);
	public GUI ()
	{
		
		initComponents();
		testUDPReceiveText = new UdpReceiver(listeningPort, textRec);
		(new Thread(testUDPReceiveText)).start();

		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	}
	
	private void initComponents() {
		
		
		
		 // create the components
		textRec = new JTextArea(3,25);
		textRec.setEditable(false);
		textToSend = new JTextArea(3,25);
		bSend = new JButton("Send");
		connect = new JButton("Connect");
		disconnect = new JButton("Disconnect");
		login = new JTextField();
		login.setEditable(true);
		
		this.setLayout(new GridLayout(3,2));
		this.add(new JScrollPane(textToSend));
		this.add(new JScrollPane(textRec));
        this.add(bSend);
        this.add(login);
        this.add(connect);
        this.add(disconnect);
        bSend.addActionListener(new ButtonSendListener());
        connect.addActionListener(new ButtonConnectListener());
        disconnect.addActionListener(new ButtonDisconnectListener());
		this.pack();
		this.setVisible(true);
	}
	
	
	public class ButtonSendListener implements ActionListener  
	{
		public void actionPerformed (ActionEvent e)
		{
			String msg;
			try
			{
				//msg = new BufferedReader(new InputStreamReader(System.in)).readLine();
				msg = textToSend.getText();
				System.out.println(msg);
				(new UdpSender(portDest)).sendText(InetAddress.getLocalHost(),msg, portDest);
			}catch (IOException e1) {
				System.out.println("Impossible d'envoyer le msg");
				e1.printStackTrace();
			}
		}
	}
	
	public class ButtonConnectListener implements ActionListener  
	{
		public void actionPerformed (ActionEvent e)
		{
			performConnex = new PerformConnexion(getChat());
		}
	}
	
	public class ButtonDisconnectListener implements ActionListener  
	{
		public void actionPerformed (ActionEvent e)
		{
			performDisconnex = new PerformDisconnect(getChat());
		}
	}
	public GUI getChat()
	{
		return this;
	}
	
	public JTextArea getText()
	{
	  return textRec;
	}
	public String getUser()
	{
	  String name;
	  JTextField text;
	  text = login;
	  name = text.getText();
	  System.out.println(name);
	  return name;
	}
	
	public static void main(String[] args) 
	{
	    GUI f = new GUI();   
	}

}
